#!/usr/bin/python
# -*- coding:utf-8 -*-
#购物清单写在文件里，用户可以查询历史购买物品，用户有余额

# ####################################读取文件列表####################################
#   ###############读取用户信息###############
f1 = open('user_info','r')
data = f1.read()
f1.close()

user_info_list = []#用户信息列表
user_str_list = [i for i in data.split('\n') if i]  # 移除data.split()生成的空元素
for item in user_str_list:
    temp = item.split('|')
    v = {
        'username': temp[0],
        'password': temp[1],
        'times': temp[2],
        'money':int(temp[3])
    }
    user_info_list.append(v)
# print(user_info_list)
#   ####################读取商品列表###########
f3 = open('goods_list','r',encoding='utf-8')#需要转为utf-8
data = f3.read()
f3.close()
goods_list = []#商品信息列表
goods_str_list = [i for i in data.split('\n') if i]  # 移除data.split()生成的空元素
for goods_item in goods_str_list:
    temp = goods_item.split('|')
    v = {
        'goods_name': temp[0],
        'goods_price': temp[1],
        }
    goods_list.append(v)
# ###################################时间
import datetime
import time
now_time = time.strftime("%Y-%m-%d  %X",time.localtime())
# print(now_time)
# #######################################用户登录##################################
message_login = '%s欢迎您，账户余额：%d'#登录成功显示用户基本信息
message_totle_price="账单总金额：%d"
shopping_price_totle=0
shopping_car=[]
shopping_list = []
history_shopping_list= []
history_shopping_str=''
p = 1#购物列表初始页码
state_login = 3
while state_login > 0 :
    name = input("请输入用户名：")
    pwd = input("请输入密码：")
    for item in user_info_list :
        if name == item['username'] :
            if int(item['times']) > 0 :
                if pwd == item['password'] :
                    print(message_login %(name,item['money']))#登录成功展示个人信息
                    #主菜单
                    while True :
                        print("***********************************************")
                        user_chose = input("请选择您要的操作：\n1-购物\n2-查询\n3-退出\n")
                        shopping_state = True
                        if user_chose == '1':
                            # print("**********************************************")
                            while True:
                                print("*******商品列表如下：*******")
                                if shopping_state==False:
                                    print("购物清单如下：\n")
                                    print(shopping_car)
                                    print(message_totle_price %(shopping_price_totle))
                                    buy_state = input("请选择支付方式：1-余额购买   2-信用卡购买")
                                    if buy_state =='1':
                                        if shopping_price_totle > int(item['money']):
                                            print("余额不足，重新购买")
                                            shopping_car.clear()                #余额不足重新购买
                                            shopping_price_totle = 0
                                            shopping_state = True
                                        else:
                                            print("购买成功")
                                            item['money']=int(item['money'])-shopping_price_totle
                                            for shopping_car_item in shopping_car:
                                                shopping_list.append(shopping_car_item)
                                    elif buy_state =='2':
                                        print("信用卡连接等待中================")
                                        import ATM
                                        ATM.pay(money=shopping_price_totle)
                                        for shopping_car_item in shopping_car:
                                            shopping_list.append(shopping_car_item)
                                        break

                                    else:
                                        print('请选择正确付款方式！')
#   ##################################把用户购物记录写入文件##################################
                                    shopping_line = ''
                                    # i = 1
                                    for item5 in shopping_list:
                                        shopping_line = '\n'+shopping_line + name + '|' + item5+"| "+now_time
                                    # 写入文件
                                    f4 = open("dodo_shopping_log", 'a',encoding='utf-8')
                                    f4.write(shopping_line)
                                    f4.close()
                                    ######################写入余额############
                                    line = ''
                                    i = 1
                                    for item2 in user_info_list:
                                        if i < user_info_list.__len__():
                                            line = line + item2['username'] + '|' + item2['password'] + '|' + str(
                                                item2['times']) + '|' + str(item2['money']) + '\n'
                                            i = i + 1
                                        else:
                                            line = line + item2['username'] + '|' + item2['password'] + '|' + str(
                                                item2['times']) + "|" + str(item2['money'])

                                    # 写入文件
                                    f2 = open("user_info", 'w')
                                    f2.write(line)
                                    f2.close()
                                    break
                                else:
                                    #显示购物列表
                                    if len(goods_list)%5 > 0 :
                                        totle_page = str(int(len(goods_list) / 5) + 1)
                                    else:
                                        totle_page = str(int(len(goods_list) / 5) )
                                    print("商品名称     " + "|" + "     商品价格     ")
                                    print("--------------------------")
                                    start = (p - 1) * 5
                                    end = p * 5
                                    for i in goods_list[start:end]:
                                        v = i['goods_name']
                                        v1 = v.ljust(9)
                                        v1 = v1.replace(' ', '  ')
                                        v2 = i['goods_price']
                                        # 分页显示
                                        print(v1, v2)
                                    print(str(p) + '/' + totle_page)# 显示当前页数
                                    shopping = input(('请输入您想要购买物品的名称\n没有想要商品继续浏览请按任意键\n结账请按-0：'))
                                    if shopping == '0':
                                        shopping_state  = False
                                    else:
                                        for items in goods_list:
                                            if shopping == items['goods_name'] :
                                                shopping_car.append(shopping)
                                                shopping_price_totle += int(items['goods_price'])
                                                break
                                        else:
                                            pass
                                        p = int(input("请输入页码(请输入整数) 结账请按-0："))
                                        if p != 0:continue
                                        else:shopping_state =False

                        elif user_chose =='2':
                            # print(history_shopping)
                            #把所有商品拼接成一个字符串
                            #   #################读取用户历史购买记录###########
                            f5 = open('dodo_shopping_log', 'r',encoding='utf-8')
                            history_data = f5.read()
                            f5.close()

                            history_shopping_list = []  # 用户信息列表
                            history_shopping_str = [i for i in history_data.split('\n') if i]  # 移除data.split()生成的空元素
                            for read_history_item in history_shopping_str:
                                temp = read_history_item.split('|')
                                v = {
                                    'log_goods': temp[1],
                                    'log_time': temp[2],
                                    'log_username': temp[0]
                                    }
                                history_shopping_list.append(v)
                            # print(history_shopping_list)
                            history_state = input("1-查询所有记录     2-查询历史商品")
                            if history_state == '2':
                                history_goods = input("请输入您要查询的商品：")
                                for item6 in history_shopping_list :
                                    # print(item6['log_username'])

                                    if history_goods in item6['log_goods'] and name == item6['log_username']:
                                # if history_goods in history_data :
                                        print("您购买过！")
                                        break
                                else:
                                    print('您没有买过')
                            else:#查询所有记录
                                for item7 in history_shopping_list:
                                    if name==item7['log_username']:
                                        print(item7['log_username']+'|'+item7['log_goods']+'|'+item7['log_time'])
                        else:
                            print("欢迎下次再来！再见")
                            break
                    state_login =0
                    item['times']=3
                    state_login = 0
                    break

                else:
                    state_login -= 1
                    if state_login == 0:
                        print("尝试次数超限，登录失败")
                    else:
                        print("输入有误!，请重新输入")

                    item['times']=int(item['times'])-1
                    break
            else:
                print("用户已被锁定！")
                state_login = 0
                break
    else :
        state_login -= 1
        if state_login == 0 :
            print("尝试次数超限，登录失败")
        else:
            print("输入有误，请重新输入")
#print(db_list)
########################################变成字符串##############################
line =''
i = 1
for item2 in user_info_list :
    if i<user_info_list.__len__():
        line = line+item2['username']+'|'+item2['password']+'|'+str(item2['times'])+'|'+str(item2['money'])+'\n'
        i=i+1
    else :
        line =line+item2['username']+'|'+item2['password']+'|'+str(item2['times'])+"|"+str(item2['money'])
# m ="zhi:%r"
# print(m %(line))
#写入文件
f2 = open("user_info",'w')
f2.write(line)
f2.close()
